package com.atguigu.gulimall.product.exception;

import com.atguigu.common.exception.BizCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import com.atguigu.common.utils.R;

import java.util.HashMap;

/**
* 功能：集中的处理product服务的所有异常
* */
@Slf4j
@RestControllerAdvice(basePackages = "com.atguigu.gulimall.product.controller")
public class ExceptionControllerAdvice {
	/**
	 * 处理后端数据校验相关的异常
	 * */
	@ExceptionHandler(value = MethodArgumentNotValidException.class)
	public R handlerVaildException(MethodArgumentNotValidException e){
		log.error("数据校验出现问题{}，异常类型是{}",e.getMessage(),e.getClass());
		BindingResult result = e.getBindingResult();
		HashMap<String, Object> errMap = new HashMap<>();
		result.getFieldErrors().forEach((item)->{
			errMap.put(item.getField(),item.getDefaultMessage());
		});
		return R.error(BizCodeEnum.VAILD_EXCEPTION.getCode(),BizCodeEnum.VAILD_EXCEPTION.getMsg()).put("data",errMap);
	}

	/**
	*通用异常处理
	* */
	@ExceptionHandler(value = Throwable.class)
	public R commonExceptionHandle(Throwable e){
		return R.error(BizCodeEnum.UNKNOW_EXCEPTION.getCode(),e.getMessage());
	}
}
